import requests
import sys
import json
from time import sleep
sys.path.append('../文库登录')
from common_api import get_headers

# 目标URL
url = "https://cuttlefish.baidu.com/user/interface/getquerypacklist"

# 请求头，伪装成浏览器
headers = get_headers()

# 要循环的参数值列表0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
cid_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,99]
pn_values = range(30)  # pn取值范围是0到29--30

# 保存结果的文件名
output_file = 'query_results.txt'

# 循环遍历所有参数组合
with open(output_file, 'w', encoding='utf-8') as f_out:
    for cid in cid_values:
        for pn in pn_values:
            # 请求参数
            params = {
                'cid': cid,
                'pn': pn,
                'rn': 20,  # 每页数量固定为20
                'word': '',
                'tab': 1
            }
            # 发送请求
            response = requests.get(url, headers=headers, params=params)
            sleep(10)
            # 检查响应状态码
            if response.status_code == 200:
                # 输出返回的JSON数据
                data = response.json()
                print(data)
                query_list = data['data']['queryList']
                for item in query_list:
                    f_out.write(json.dumps(item, ensure_ascii=False) + '\n')
            else:
                print(f"Failed to retrieve data for cid={cid}, pn={pn}, status code: {response.status_code}")

